package org.thulearn.htmlparser;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.thulearn.model.ConstData;
import org.thulearn.model.TaskAttachment;
import org.thulearn.model.TaskDetail;

public class ParseTaskDetail {
	static public void parseTaskDetail(String html, TaskDetail taskDetail){
		Parser taskDetailParser = Parser.createParser(html, "utf-8");
		try {
			NodeList tableList = taskDetailParser.extractAllNodesThatMatch(new NodeFilter() {
				/**
				 * 
				 */
				private static final long serialVersionUID = 1L;

				@Override
				public boolean accept(Node node ) {
					if(node instanceof TableTag)
						return true;
					return false;
				}
			});
			for(int i = 0; i < tableList.size(); i++) {
				if(i == 1) {
					TableTag table = (TableTag) tableList.elementAt(i);
					TableRow row[] = table.getRows();
					
					String introduction = row[1].getColumns()[1].toPlainTextString().trim();
					
					String titleAndLinkString = ParserUtil.parseLink(row[2].getColumns()[1].toHtml());
					TaskAttachment taskAttachment = new TaskAttachment();
					if(!titleAndLinkString.equals("")) {
						String array[] = titleAndLinkString.split(" ");
						taskAttachment.setTitle(array[0]);
						taskAttachment.setUrl(array[1]);
					} else {
						taskAttachment.setTitle(ConstData.getNoTaskAttachmentString());
						taskAttachment.setUrl("");
					}
					
					String committedContent = row[4].getColumns()[1].toPlainTextString().trim();
					
					titleAndLinkString = ParserUtil.parseLink(row[5].getColumns()[1].toHtml());
					TaskAttachment committedAttachment = new TaskAttachment();
					if(!titleAndLinkString.equals("")) {
						String array[] = titleAndLinkString.split(" ");
						committedAttachment.setTitle(array[0]);
						committedAttachment.setUrl(array[1]);
					} else {
						committedAttachment.setTitle(ConstData.getNoTaskAttachmentString());
						committedAttachment.setUrl("");
					}
					
					taskDetail.setIntroduction(introduction);
					taskDetail.setCommittedContent(committedContent);
					taskDetail.setTaskAttachment(taskAttachment);
					taskDetail.setCommittedAttachment(committedAttachment);
				}
			}
			
		} catch (ParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
